""" 

    quizanswer.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which checks your answers to the quiz against what is stored in the datastore.
    Then it returns the quiz results as a JSON object.
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from facebook import FacebookError
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from utils import fbUtil, dbUtil, Pledges, Challenges, Leaderboard

class MainHandler(webapp.RequestHandler):
    
    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "youranswers":[], "correctanswers":[], "maxpoints": 0}
        
        try:
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "not logged in"
            else:
                user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
                userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
                
                if userInfo is  None:
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "no legislators stored for you"  
                else:
                    
                    answers = ["", "", ""]
                    answers[0] = self.request.get('rep', default_value="")
                    answers[1] = self.request.get('jrsen', default_value="")
                    answers[2] = self.request.get('srsen', default_value="")
                    jsonOutput["youranswers"] = answers
                    
                    correctanswers = ["","",""]
                    if userInfo.has_key("rep"):
                        correctanswers[0] = userInfo["rep"]
                    if userInfo.has_key("jrsen"):
                        correctanswers[1] = userInfo["jrsen"]
                    if userInfo.has_key("srsen"):
                        correctanswers[2] = userInfo["srsen"]
                    jsonOutput["correctanswers"] = correctanswers
                
                    pointvalue = [3,1,1]
                    for i in range(3):
                        if (answers[i] == "nothing") or (correctanswers[i] == ""):
                            pointvalue[i] = 0
                            
                    yourscore = 0
                    theirscore = 0
                    for i in range(3):
                        jsonOutput["maxpoints"] = jsonOutput["maxpoints"] + pointvalue[i]
                        if correctanswers[i] == answers[i]:
                            yourscore = yourscore + pointvalue[i]
                        else:
                            theirscore = theirscore + pointvalue[i]
                    
                    challenger = 0       
                    query = Challenges.all()
                    query.filter("challengee =", int(self.facebookapi.uid))
                    query.filter("completed =", False)
                    results = query.fetch(1)
                    for result in results:
                        challenger = result.challenger
                        result.completed = True
                        result.challengeescore = yourscore
                        result.challengerscore = theirscore
                        result.put()
            
                    challengerBoard = Leaderboard.get_or_insert("user"+str(challenger), uid=challenger)
                    challengerBoard.score = challengerBoard.score + theirscore
                    challengerBoard.put()
            
                    challengeeBoard = Leaderboard.get_or_insert("user"+str(self.facebookapi.uid), uid=int(self.facebookapi.uid))
                    challengeeBoard.score = challengeeBoard.score + yourscore
                    challengeeBoard.put()

                        
        except FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput))          
  
def main():
	application = webapp.WSGIApplication([('/fb/quizanswer', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
